from flask import request
from typing import Dict, Any
from tools.hotnews import get_platform_news, PLATFORMS, fetch_hot_news
import random


def register_api_routes(app, ht_app):
    ht_app.logger.debug(f"进入 register_api_routes 函数，ht_app 类型: {type(ht_app)}, id: {id(ht_app)}")
    """
    注册API路由
    
    Args:
        app: Flask应用实例
        ht_app: Hot TopicApp实例
    """

    @app.route('/api/hot-topics', methods=['GET'])
    def get_hot_topics():
        """获取热点话题列表"""
        return _get_hot_topics(ht_app)

    @app.route('/api/status', methods=['GET'])
    def system_status():
        """系统状态检查"""
        return _system_status(ht_app)

    @app.route('/api/filtered-trends', methods=['GET'])
    def get_filtered_trends_api():
        """获取经过关键词过滤和热度计算的趋势话题"""
        return _get_filtered_trends(ht_app)

    @app.route('/api/all-platform-first-hot-topics', methods=['GET'])
    def get_all_platform_first_hot_topics():
        """获取所有平台的第一个热门热点"""
        return _get_all_platform_first_hot_topics(ht_app)

    @app.route('/api/get_content', methods=['GET'])
    def get_content():
        """获取指定路径的文件内容"""
        return _get_content(ht_app)


def _get_hot_topics(ht_app) -> Dict[str, Any]:
    """
    获取热点话题列表
    
    Args:
        ht_app: Hot TopicAPP实例
        
    Returns:
        dict: API响应
    """
    ht_app.logger.debug("进入 _get_hot_topics 函数") # 新增日志
    try:
        platform = request.args.get('platform', '微博')
        count = int(request.args.get('count', 30))

        ht_app.logger.info(f"获取热点话题: 平台={platform}, 数量={count}")

        # 获取热点新闻数据
        news_data = get_platform_news(platform, count)

        if not news_data:
            return {
                'success': False,
                'error': f'无法获取{platform}的热点话题',
                'data': []
            }

        # 对lastCount为0的数据进行处理，赋予一个随机值
        for item in news_data:
            original_last_count = item.get('lastCount')
            ht_app.logger.info(f"处理话题: {item.get('name')}, 原始lastCount: {original_last_count}, 类型: {type(original_last_count)}")
            # 兼容整数0和字符串"0"的情况，以及负数情况
            if original_last_count is None or original_last_count == 0 or str(original_last_count).strip() == '0':
                new_last_count = random.randint(1000, 5000)
                item['lastCount'] = new_last_count
                ht_app.logger.info(f"修改lastCount: 平台={platform}, 话题={item.get('name')}, 原始值={original_last_count}, 新值={new_last_count}")
            elif isinstance(original_last_count, (int, float)) and original_last_count < 0:
                item['lastCount'] = 0
                ht_app.logger.info(f"将负数lastCount修改为0: 平台={platform}, 话题={item.get('name')}, 原始值={original_last_count}, 新值={0}")
            else:
                ht_app.logger.info(f"未修改lastCount: 平台={platform}, 话题={item.get('name')}, 当前值={original_last_count}")

        return {
            'success': True,
            'data': {
                'platform': platform,
                'topics': news_data,  # 返回完整的新闻数据，包含name, rank, lastCount, url
                'count': len(news_data)
            }
        }

    except Exception as e:
        ht_app.logger.error(f"获取热点话题失败: {e}")
        return {
            'success': False,
            'error': f'获取热点话题失败: {str(e)}',
            'data': []
        }


def _system_status(ht_app) -> Dict[str, Any]:
    """
    系统状态检查
    
    Args:
        ht_app: Hot TopicAPP实例
        
    Returns:
        dict: API响应
    """
    try:
        # 检查AI API
        ai_model = ht_app.config.get_ai_model()
        ai_status = ht_app.ai_client.test_connection()

        status = {
            f'{ai_model}_api': ai_status,
            'wechat_api': ht_app.wechat_publisher.test_connection(),
            'wechat_verified': ht_app.wechat_publisher.is_verified()
        }

        # 判断整体状态
        if ai_status and status['wechat_api']:
            overall = 'healthy'
            message = f'所有服务运行正常 (AI模型: {ai_model.upper()})'
        elif ai_status or status['wechat_api']:
            overall = 'partial'
            message = f'部分服务可用 (AI模型: {ai_model.upper()})'
        else:
            overall = 'error'
            message = f'服务异常，请检查配置 (AI模型: {ai_model.upper()})'

        return {
            'success': True,
            'data': {
                'status': status,
                'overall': overall,
                'message': message
            }
        }

    except Exception as e:
        ht_app.logger.error(f"系统状态检查失败: {e}")
        return {
            'success': False,
            'error': f'系统状态检查失败: {str(e)}'
        }

def _get_filtered_trends(ht_app) -> Dict[str, Any]:
    """
    获取热点趋势数据，按 platform 分组，返回全部结果，无数量限制

    Args:
        ht_app: Hot TopicAPP 实例

    Returns:
        dict: {success: bool, data: {platform: {count: int, topics: list}}}
    """
    try:
        ht_app.logger.info("获取分组热点趋势（无数量限制）...")

        # 调用你的方法获取原始数据
        trends_data = fetch_hot_news()

        if not trends_data:
            return {
                'success': False,
                'error': 'fetch_hot_news 返回空数据',
                'data': {}
            }

        # 按 platform 分组
        grouped_data = {}
        for item in trends_data:
            platform = item['platform']
            if platform not in grouped_data:
                grouped_data[platform] = {
                    'count': 0,
                    'topics': []
                }
            grouped_data[platform]['topics'].append(item)
            grouped_data[platform]['count'] += 1  # 累加计数

        return {
            'success': True,
            'data': grouped_data
        }

    except Exception as e:
        ht_app.logger.error(f"生成分组热点趋势失败: {str(e)}")
        return {
            'success': False,
            'error': f'处理热点数据时出错: {str(e)}',
            'data': {}
        }


def _get_all_platform_first_hot_topics(ht_app) -> Dict[str, Any]:
    """
    获取所有平台的第一个热门热点

    Args:
        ht_app: Hot TopicAPP 实例

    Returns:
        dict: {success: bool, data: list}
    """
    try:
        ht_app.logger.info("获取所有平台的第一个热门热点...")
        all_first_hot_topics = []
        for platform_info in PLATFORMS:
            platform_name = platform_info['name']
            # 尝试获取该平台的热点新闻，只取第一个
            news_data = get_platform_news(platform_name, 1)
            if news_data:
                all_first_hot_topics.append({
                    'platform': platform_name,
                    'topic': news_data[0]
                })
        return {
            'success': True,
            'data': all_first_hot_topics
        }
    except Exception as e:
        ht_app.logger.error(f"获取所有平台第一个热门热点失败: {str(e)}")


def _get_content(ht_app) -> Dict[str, Any]:
    """
    获取指定路径的文件内容

    Args:
        ht_app: Hot TopicAPP 实例

    Returns:
        dict: API响应
    """
    try:
        file_path = request.args.get('file_path')
        if not file_path:
            return {
                'success': False,
                'error': '缺少文件路径参数'
            }

        # 确保文件路径安全，避免目录遍历攻击
        # 这里需要根据实际项目结构调整，确保只允许访问特定目录下的文件
        # 例如，可以检查文件路径是否在允许的根目录下
        # if not file_path.startswith('allowed_base_path'):
        #     return {'success': False, 'error': '非法文件路径'}

        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()

        return {
            'success': True,
            'data': {
                'file_path': file_path,
                'content': content
            }
        }

    except FileNotFoundError:
        ht_app.logger.error(f"文件未找到: {file_path}")
        return {
            'success': False,
            'error': f'文件未找到: {file_path}'
        }
    except Exception as e:
        ht_app.logger.error(f"获取文件内容失败: {e}")
        return {
            'success': False,
            'error': f'获取文件内容失败: {str(e)}'
        }
